import * as base64 from 'base-64';
import CryptoJs from 'crypto-js';
import { requestObj } from '@/config/ai.js';

export const getWebsocketUrl = async () => {
  return new Promise((resovle, reject) => {
    var apiKey = requestObj.APIKey
    var apiSecret = requestObj.APISecret
    var url = 'wss://spark-api.xf-yun.com/v4.0/chat'
    var host = location.host
    var date = new Date().toGMTString()

    var algorithm = 'hmac-sha256'
    var headers = 'host date request-line'
    var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v4.0/chat HTTP/1.1`
    var signatureSha = CryptoJs.HmacSHA256(signatureOrigin, apiSecret)
    var signature = CryptoJs.enc.Base64.stringify(signatureSha)
    var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`
    var authorization = base64.encode(authorizationOrigin)

    url = `${url}?authorization=${authorization}&date=${date}&host=${host}`
    resovle(url)
  });
};